<?php
use think\Db;
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
error_reporting(E_ERROR | E_PARSE );

/**
 * 统一api返回函数
 * @Author   CCH
 * @DateTime 2020-05-23T12:19:19+0800
 * @param    code   结果编码
 * @param    msg    说明
 * @param    data   数据
 * @return   统一格式返回json
 */
// function apiResult($code,$msg='',$data=null){
//     $result = ['code'=>$code];
//     !empty($msg) && $result['msg'] = $msg;
//     if ( !is_null($data) ) {
//       is_object($data) && $data = $data->toarray();
//       // if (is_array($data)) {
//       //   array_walk_recursive($data,function(&$data_v,$key){
//       //     if($data_v === null){ $data_v = ''; }
//       //   });
//       // }
//       if ( isset($data['data']) ) {
//         $result['result'] = $data;
//       }else{
//         $result['result'] = array();
//         $result['result']['data'] = $data;  
//       }
//     }
//     return json($result);
// }

function timeDef($val, $default = "", $format = 'Y-m-d H:i'){
    return empty($val) ? $default : date($format,$val);
}
// 格式化日期
function timeFormat($val,$format = 'Y-m-d H:i'){
    if (empty($val)) {
        return '';
    }
    return date($format,strtotime($val));
}

function actionCn($key){
	$list = [
		'index'=>'列表',
		'add'=>'新增',
		'edit'=>'编辑',
		'view'=>'详情',
		'delete'=>'删除'
	];
	return $list[$key];
}

// url默认空链接
function urlDef($url){
	return empty($url) ? 'javascript:void(0)' : $url;
}

// 将数组参数提取出来
function arrayParamExtract($list,$key,$val){
    $result = [];
    foreach ($list as $k => $vo) {
        $result[$vo[$key]] = $vo[$val];
    }
    return $result;
}

// 生成 增/改 页面校验
function createPageValid($fields=[]){
	$rules = [];
    $messages = [];
    foreach ($fields as $field => $vo) {
        if (!empty($vo['valids'])) {
            $rule = [];
            $message = [];
            foreach ($vo['valids'] as $valid) {
                $rule[$valid] = true;
                $message[$valid] = '请输入'.$vo['name'];
            }
            $rules[$field] = $rule;
            $messages[$field] = $message;
        }
    }
    if (empty($rules)) {
		return [];
	}
	return ['rules'=>$rules,'messages'=>$messages];
}
// function createPageValid($fields=[]){
//     $valids = [];
//     foreach ($fields as $field => $vo) {
//         if (!empty($vo['valids'])) {
//             $valids[$field] = ['validators'=>[]];
//             foreach ($vo['valids'] as $valid) {
//                 $valids[$field]['validators'][$valid]['message'] = '请输入'.$vo['name'];
//             }
//         }
//     }
//     if (empty($valids)) {
//         return [];
//     }
//     return $valids;
// }

// 空默认
function emptyDef($val, $default="", $type='empty') {
    switch ($type) {
        case 'empty':
            return empty($val) ? $default : $val;
            break;
        case 'isset':
            return isset($val) ? $val : $default;
            break;
        default:
            return empty($val) ? $default : $val;
            break;
    }
}

/**
 * 创建多个重复字符拼接字符串
 * @Author   CCH
 * @DateTime 2020-08-15T23:05:10+0800
 * @param    $str  重复字符
 * @param    $num  重复次数
 * @param    $join 拼接符号
 * @return   拼接后字符串
 */
function stringRange($str,$num=1,$join=''){
    $result = [];
    for ($i=0; $i < $num; $i++) { 
        $result[] = $str;
    }
    return implode($join, $result);
}

// 随机颜色
// function randomColor(){
//     mt_srand((double)microtime()*1000000);
//     $c = '';
//     while(strlen($c)<6){
//         $c .= sprintf("%02X", mt_rand(0, 255));
//     }
//     return $c;
// }

// 判断是否加入筛选
function getSearchParam($params,$prefix=''){
    $map = [];
    foreach ($params as $key => $param) {
        if ( isSearchParam($param['key']) ) {
            switch ($param['type']) {
                case '=': 
                    $map[] = [$prefix.$param['key'],'=',input($param['key'])];
                    break;
                case '>': 
                    $map[] = [$prefix.$param['key'],'>',input($param['key'])];
                    break;
                case '>=': 
                    $map[] = [$prefix.$param['key'],'>=',input($param['key'])];
                    break;
                case '<': 
                    $map[] = [$prefix.$param['key'],'<',input($param['key'])];
                    break;
                case '<=': 
                    $map[] = [$prefix.$param['key'],'<=',input($param['key'])];
                    break;
                case 'like': 
                    $map[] = [$prefix.$param['key'],'like','%'.input($param['key']).'%'];
                    break;
                default: break;
            }
        }
    }
    return $map;
}

function isSearchParam($param){
    return input($param,null) != null;
}

// 是否下拉选中
function isSelected($val1, $val2, $res = "selected") {
    if (!isset($val1) || !isset($val2)) {
        return "";
    }
    return (string)$val1==(string)$val2?$res:"";
} 

// 参数过滤（筛选）
function paramFilter($params,$fields=[]){
    $result = [];
    foreach ($fields['must'] as $k => $field) {
        if (empty($params[$field]) && $params[$field] != '0') {
            return ['error_msg'=>'参数不能为空('.$field.')'];
        }
        $result[$field] = $params[$field];
    }
    // foreach ($fields['onemust'] as $k => $field_list) {
    //     $is_exist = false;
    //     foreach ($field_list as $field) {
    //         if ( !empty($params[$field]) ) {
    //             $result[$field] = $params[$field];
    //             $is_exist = true;
    //             break;
    //         }
    //     }
    //     if (!$is_exist) {
    //         return ['error_msg'=>'参数不能为空('.implode(' | ', $field_list).')'];
    //     }
    // }
    foreach ($fields['nomust'] as $k => $field) {
        isset($params[$field]) && $result[$field] = $params[$field];
    }
    return $result;
}

// textarea正常显示
function myTextareaShow($content){
    // return str_replace(" ","&nbsp;",str_replace("\n","<br/>",$content)); 
    return str_replace("\n","<br/>",$content); 
}

/**
 * 生成UUID
 * @Author   CCH
 * @DateTime 2020-05-23T11:59:13+0800
 * @return   UUID
 */
function uuidCreate() {
    if (function_exists('com_create_guid')){
       $uuid = com_create_guid();
    }else{
       mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
       // $charid = strtoupper(md5(uniqid(rand(), true)));
       $charid = md5(uniqid(rand(), true));
       $hyphen = chr(45);
       $uuid = chr(123)
               .substr($charid, 0, 8).$hyphen
               .substr($charid, 8, 4).$hyphen
               .substr($charid,12, 4).$hyphen
               .substr($charid,16, 4).$hyphen
               .substr($charid,20,12)
               .chr(125);
    }
    $uuid = str_replace(array('{','}','-'), '', $uuid);
    return strtoupper($uuid);
} 

/**
 * 检验数据的真实性，并且获取解密后的明文.
 * @param $encrypted_data string 加密的用户数据
 * @param $iv string 与用户数据一同返回的初始向量
 * @param $data string 解密后的原文
 *
 * @return int 成功0，失败返回对应的错误码
 */
function xcxDecryptData($session_key,$encrypted_data,$iv)
{
    if (strlen($session_key) != 24) {
        return ['status'=>0,'msg'=>'错误sessionKey'];
    }
    $aesKey=base64_decode($session_key);
    if (strlen($iv) != 24) {
      return ['status'=>0,'msg'=>'错误iv'];
    }
    $aesIV=base64_decode($iv);
    $aesCipher=base64_decode($encrypted_data);
    $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
    $data = json_decode($result,true);
    if (empty($data)) {
      return ['status'=>0,'msg'=>'解密失败'];
    }
    return ['status'=>1,'data'=>$data];
}

function myExplode($str, $separator = ',')
{
    if (!empty($str)) {
        return explode($separator, $str);
    }
    return $str;
}

/**
 *  @desc 根据两点间的经纬度计算距离
 *  @param float $lat 纬度值
 *  @param float $lng 经度值
 */
function getDistance($lat1, $lng1, $lat2, $lng2) {
    $earthRadius = 6371000;
    $lat1 = ($lat1 * pi() ) / 180;
    $lng1 = ($lng1 * pi() ) / 180;

    $lat2 = ($lat2 * pi() ) / 180;
    $lng2 = ($lng2 * pi() ) / 180;

    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;
    return round($calculatedDistance);
}

/**
 * 二位数组根据某个字段排序
 * @Author   CCH
 * @DateTime 2020-05-24T13:14:15+0800
 * @param    $arr        排序数组
 * @param    $field_name 字段名
 * @param    $sort_type  排序方式
 * @return   排序后数组
 */
function arrSortByField($arr, $field_name, $sort_type = SORT_ASC) {
    $fields  = array_column($arr,$field_name);
    array_multisort($fields, $sort_type, $arr);
    return $arr;
}

// xml转数组
function xmlToArray($xml){
    return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
}



/**
 * 上传文件
 * @Author   CCH
 * @DateTime 2020-05-23T12:20:41+0800
 * @param    file   file文件对象
 * @return   上传结果
 */
// function uploadFile($file_name,$tmp_name,$path=''){
//     try{
//         $config = config('config.aliyun_oss');
//         $object = $path.uuidCreate().'.'.pathinfo($file_name,PATHINFO_EXTENSION);
//         $oss = new \OSS\OssClient($config['keyId'],$config['keySecret'],$config['endpoint']);
//         $result = $oss->uploadFile($config['bucket'], $object, $tmp_name);
//         return ['status'=>1,'data'=>$object];
//     } catch(OssException $e) {
//         return ['status'=>0,'msg'=>$e->getMessage()];
//     }
//     return true;
// }
// function uploadFile($file_name,$tmp_name,$path=''){
//     try{
//         $file = request()->file('file');
//         $info = $file->move('./uploads');
//         if(!$info){
//             return ['status'=>0,'msg'=>'fail'];
//         }
//         return ['status'=>1,'data'=>str_replace('\\', '/', $info->getSaveName())];
//     } catch(OssException $e) {
//         return ['status'=>0,'msg'=>$e->getMessage()];
//     }
//     return true;
// }

/**
 * CURL请求
 * @Author   CCH
 * @DateTime 2020-06-07T17:14:32+0800
 * @param    $url    [description]
 * @param    string                   $data   [description]
 * @param    string                   $method [description]
 * @return           [description]
 */
function httpRequest($url, $data='', $method='GET',$header=[],$timeout=20){
    $curl = curl_init();  
    curl_setopt($curl, CURLOPT_URL, $url);  
    if(strpos($url,'https') !== false){
        // curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 ); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    }
    // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);  
    // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);  
    // curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);  
    // curl_setopt($curl, CURLOPT_AUTOREFERER, 1);  
    if($method=='POST') {
        curl_setopt($curl, CURLOPT_POST, 1); 
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);  
    }
    if (!empty($header)) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    }
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);  
    curl_setopt($curl, CURLOPT_HEADER, 0);  
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
    $result = curl_exec($curl);  
    curl_close($curl);  
    return $result;
} 

function xml_data($url,$xmlData,$timeout=20){
    $header = array();
    $header[] = "Content-type: text/xml";      //定义content-type为xml,注意是数组
    $ch = curl_init ($url);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); 
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

//导出csv格式
// function downloadFile( $file_path  ) {
//     $excel = new \PHPExcel();
//     $excel_sheet = $excel->getActiveSheet();
//     $excel_sheet->fromArray($data);
//     $excel_writer = \PHPExcel_IOFactory::createWriter($excel,'Excel2007');

//     $file_name = '用户数据.xlsx';
//     $file_path = './excel/'.$file_name;
//     $excel_writer->save($file_path);
//     if (!file_exists($file_path)) {
//         throw new \Exception("Excel生成失败");
//     }

//     $paths = explode('/', $file_path);
//     $contents = file_get_contents($file_path);
//     $file_size = filesize($file_path);
//     header("Content-type: application/octet-stream;charset=utf-8");
//     header("Accept-Ranges: bytes");
//     header("Accept-Length: $file_size");
//     header("Content-Disposition: attachment; filename=".$paths[count($paths)-1]);
//     echo $contents;
// }
// 下载excel
function downloadFile( $file_name , $data  ) {
    try{
        $excel = new \PHPExcel();
        $excel_sheet = $excel->getActiveSheet();
        $excel_sheet->fromArray($data);
        $excel_writer = \PHPExcel_IOFactory::createWriter($excel,'Excel2007');

        $file_path = './excel/'.$file_name;
        $excel_writer->save($file_path);
        if (!file_exists($file_path)) {
            throw new \Exception("Excel生成失败");
        }

        $paths = explode('/', $file_path);
        $contents = file_get_contents($file_path);
        $file_size = filesize($file_path);
        header("Content-type: application/octet-stream;charset=utf-8");
        header("Accept-Ranges: bytes");
        header("Accept-Length: $file_size");
        header("Content-Disposition: attachment; filename=".$file_name);
        echo $contents;
    } catch (\Exception $e) {
        return ['status'=>0,'msg'=>$e->getMessage()];
    }
}

// function writeLog($type,$content=''){
//     $space = "    ";
//     switch ($type) {
//         case 'order':
//             $dirpath = './logs/'.date("Ymd",time());
//             if (!is_dir($dirpath)) { mkdir($dirpath); }
//             $filename = $dirpath.'/'.date('H').'.txt';

//             $filecontent = date("Y-m-d H:i:s").$space.'ipaddr'.$space.$content."\n";
//             $result = file_put_contents($filename, $filecontent,FILE_APPEND);
//             break;
//         case 'search':
//             $dirpath = './logs/search';
//             // if (!is_dir($dirpath)) { mkdir($dirpath); }
//             $filename = $dirpath.'/'.date("Ymd").'.txt';

//             $filecontent = date("Y-m-d H:i:s").$space.'ipaddr'.$space.$content."\n";
//             $result = file_put_contents($filename, $filecontent,FILE_APPEND);
//             break;
//         case 'error':
//             $dirpath = './logs/error';
//             // if (!is_dir($dirpath)) { mkdir($dirpath); }
//             $filename = $dirpath.'/'.date("Ymd").'.txt';

//             $filecontent = date("Y-m-d H:i:s").$space.'ipaddr'.$space.$content."\n";
//             $result = file_put_contents($filename, $filecontent,FILE_APPEND);
//             break;
//         default: break;
//     }
//     return $result;
// }
function writeLog($type,$content=''){
    $space = "    ";
    $filecontent = date("Y-m-d H:i:s").$space.'ipaddr'.$space.$content."\n";
    $api_url = config('config.system.logs_url');
    $result = post_data($api_url,['type'=>$type,'content'=>$filecontent],1);
    return ture;
}

function apiResult($result,$type='order'){
    try {
        $content = json_encode(request()->param())."，结果：".json_encode($result,JSON_UNESCAPED_UNICODE);
        writeLog($type,$content);
    } catch (\Exception $e) { }
    return json($result);
}


// 获取手机归属地 - 淘宝，部分号码运营商有误
function getMobileInfo($mobile){ 
    $res = array('province'=>'', 'catname'=>'');    //初始化变量 
    $url = 'http://cx.shouji.360.cn/phonearea.php?number='.$mobile;
    $result = @file_get_contents($url);
    $result = json_decode($result,true);
    if($result['code'] == '0'){
        $res['province'] = $result['data']['province'];
        if ($res['province'] == '海南省') {
            $res['province'] = '海南';
        }elseif ($res['province'] == '吉林省') {
            $res['province'] = '吉林';
        }
        $res['city'] = $result['data']['city'];
        $res['catname'] = $result['data']['sp'];
        switch ($res['catname']) {
            case '移动': $res['type'] = 'ChinaMobile'; break;
            case '电信': $res['type'] = 'ChinaTelecom'; break;
            case '联通': $res['type'] = 'ChinaUnicom'; break;
        }
    }
    return $res; 
}

function getProvinceList(){
    $province_list = array('江苏'=>'江苏','辽宁'=>'辽宁','福建'=>'福建','湖北'=>'湖北','广东'=>'广东','北京'=>'北京','上海'=>'上海','陕西'=>'陕西','云南'=>'云南','湖南'=>'湖南','河北'=>'河北','四川'=>'四川','山东'=>'山东','重庆'=>'重庆','黑龙江'=>'黑龙江','江西'=>'江西','新疆'=>'新疆','海南'=>'海南','浙江'=>'浙江','天津'=>'天津','山西'=>'山西','河南'=>'河南','广西'=>'广西','吉林'=>'吉林','甘肃'=>'甘肃','贵州'=>'贵州','内蒙古'=>'内蒙古','安徽'=>'安徽','西藏'=>'西藏','宁夏'=>'宁夏','青海'=>'青海','台湾省'=>'台湾省','香港特别行政区'=>'香港特别行政区','澳门特别行政区'=>'澳门特别行政区','全国'=>'全国');
    return $province_list;
}

function my_build_query($data,$is_retain=0){
    $str = '';
    foreach ($data as $k => $v) {
        $str .= $k.'='.$v.'&';
    }
    if ($str != '' && $is_retain == 0) {
        $str = substr($str,0,strlen($str)-1);
    }
    return $str;
}

// curl get请求
function get_data($url,$timeout=20) {
    //初始化
    $ch = curl_init();
    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); 
    //执行并获取HTML文档内容
    $output = curl_exec($ch);
    //释放curl句柄
    curl_close($ch);
    //打印获得的数据
    return $output;
}

// curl post请求
function post_data($url,$data,$timeout=20){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    if(strpos($url,'https') !==false){
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 ); // 对认证证书来源的检查
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // post数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // post的变量
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); 
    $output = curl_exec($ch);
    curl_close($ch);
    //打印获得的数据
    return $output;
}

// curl post请求 application/json模式
function post_json($url,$data_string,$timeout=20){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    if(strpos($url,'https') !==false){
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 ); // 对认证证书来源的检查
    }
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string))
    );
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

// 定时回调用户回调函数
function callback_timing($url,$data,$check_realtime = 1){
    $result = 'false';
    // 回调地址不为空，订单状态为成功或失败的订单，并且，用户开通实时提交和回调，才进行回调
    $uInfo = Db::name('user')->field('password,sign,is_realtime')->where('id',$data['user_id'])->find();
    if (($uInfo['is_realtime'] == 1 || $check_realtime == 0) && !empty($url) && !empty($data['order_number']) && in_array($data['order_status'], [2,-1])) {
        unset($data['user_id']);
        $data['sign'] = strtoupper(md5($uInfo['password'].$data['order_number'].$uInfo['sign']));
        $result = post_json(urldecode($url),json_encode($data),5);
        $is_callbacked = trim($result) == 'success' ? 1 : -1;
        if ($is_callbacked == -1) {
            // $logContent = '订单号：'.$data['order_number'].'，回调结果：'.$result;
            // writelog('callback',$logContent);
        }
        Db::name('order')->where('order_number',$data['order_number'])->update(['is_callbacked'=>$is_callbacked]);
    }
    return $result;
}

function showPageText($list){
    if (isset($list['total'])) {
        return $list['current_page'].' / '.$list['last_page'].' 页 ，共 '.$list['total'].' 条记录';
    }
    return '';
}


function exportCsv($title, $headArr, $exportData) {
    $total = count($exportData);
    header("Content-type:application/vnd.ms-excel");
    header("Content-Disposition:filename=" . iconv("UTF-8", "GB18030", $title) . ".csv");
    $fp = fopen('php://output', 'a');
    fputcsv($fp, $headArr);
    $size = 2000;
    $groupNum = ceil($total / $size);
    for ($i = 0; $i <= $groupNum; $i++) {
        $exportDataTemp = array_slice($exportData, $size * $i, $size);
        foreach ($exportDataTemp as $item) {
            // $rows = array();
            // foreach ($headName as $name) {
            //     $rows[] = $item[$name];
            // }
            // die;
            // fputcsv($fp, $rows);
            fputcsv($fp, $item);
        }
        ob_flush();
        flush();
    }
    die;
}

function exportReplace($str){
    return str_replace([",","\"","\r\n"],["，","'","；"],$str);
}

function indexPage($page){
    if (empty($page)) {
        return $page;
    }
    $page = preg_replace(["/<div>.*<\/div>/","(<li[^<>]*>)"],'',$page);
    $page = str_replace(['<ul class="pagination">','</li>','</ul>'],'',$page);
    return $page;
}

function categoryUrlCreate($category){
    if($category['outside_url'] == 'qrcode'){
        return 'javascript:void(0)';
    }elseif (!empty($category['outside_url'])) {
        return $category['outside_url'];
    }else{
        return url('category/index',['id'=>$category['id']]);
    }
}

// 判断是否手机号
function isMobile($mobile){
    if ( !preg_match("/^1\d{10}$/",$mobile)  ) {
        return false;
    }
    return true;
}

// 判断是否邮箱
function isEmail($email){
    if ( !preg_match('/^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/',$email) ) {
        return false;
    }
    return true;
}

// 验证码密码规范
function validatePassword($password) {
    // 检查密码长度是否不少于8位
    if (strlen($password) < 8) {
        return false;
    }
 
    // 检查是否至少有1位数字
    if (!preg_match('/[0-9]/', $password)) {
        return false;
    }
 
    // 检查是否至少有1位字母
    if (!preg_match('/[a-zA-Z]/', $password)) {
        return false;
    }
 
    // 检查是否至少有1位特殊字符
    if (!preg_match('/[!@#$%^&*]/', $password)) {
        return false;
    }
 
    // 如果所有检查都通过，则返回true
    return true;
}

function sendSms($mobile,$content,$sign='融合云'){
    if (empty($mobile) || empty($content)) {
        return false;
    }
    if (!empty($sign)) {
        $content = '【'.$sign.'】'.$content;
    }
    $api_url = 'http://47.97.215.253:8001/sms/api/sendMessage';
    $params = [
        'userName'=>'广州骉云',
        'content'=>$content,
        'phoneList'=>[$mobile],
        'timestamp'=>time().'000',
    ];
    $params['sign'] = md5($params['userName'].$params['content'].$params['timestamp'].md5('123456'));
    $api_res = httpRequest($api_url,json_encode($params,JSON_UNESCAPED_UNICODE),'POST',[
        'Content-Type: application/json'
    ]);
    $api_res = json_decode($api_res,true);
    if ($api_res['code'] == '0') {
        return ['status'=>1];
    }else{
        return ['status'=>0,'msg'=>$api_res['message']];
    }
}